package com.nwpu.coursesupport.realm;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import com.nwpu.coursesupport.enumeration.RoleType;

public class CustomizedModularRealmAuthenticator extends ModularRealmAuthenticator {
	
	 @Override
	    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
	            throws AuthenticationException {
	        CustomizedToken customizedToken = (CustomizedToken) authenticationToken;
	        RoleType roleType = customizedToken.getRoleType();
	        Collection<Realm> realms = getRealms();
	        Collection<Realm> typeRealms = new ArrayList<>();
	        for (Realm realm : realms) {
	            if (realm.getName().contains(roleType.getRoleName()))
	                typeRealms.add(realm);
	        }

	        if (typeRealms.size() == 1)
	            return doSingleRealmAuthentication(typeRealms.iterator().next(), customizedToken);
	        else
	            return doMultiRealmAuthentication(typeRealms, customizedToken);
	    }
}
